import {createRouter,createWebHashHistory} from "vue-router"
import login from '../views/login.vue'
import mainbox from '../views/mainbox.vue'
import home from '../views/home/home.vue'
import RouteConfig from './config'
import {useRouterStore} from "@/store/useRouterStore";
import NotFound from "@/views/notfound/NotFound.vue";
import  {useUserStore} from "@/store/useUserStore";


const routes = [
    {
        path:"/login",
        name:"login",
        component:login
    },
    {
        path:"/mainbox",
        name:"mainbox",
        component:mainbox
    },
    {
        path:"/home",
        name:"home",
        component:home
    }
]

const router = createRouter({
    history:createWebHashHistory(),
    routes
})

//添加路由 静态路由
// router.addRoute("mainbox",{
//     path:"/index",
//     component:home
// })

//路由拦截
router.beforeEach((to, from, next)=>{
    const  {isGetterRouter} = useRouterStore()
    const  {user} = useUserStore()

    if(to.name==="login"){
        next()
    }
    else{
        if (!user || !user.username) {  // 检查user对象和username属性
            next({ path: "/login" })

        } else{
            //第一次进入才会配置调用
            if(!isGetterRouter){
                //remove mainbox
                router.removeRoute("mainbox")
                configRouter()
                next({
                    path:to.fullPath
                })
            }else{
                next()
            }

        }
    }
    })

const configRouter = ()=>{
    //创建mainbox
    router.addRoute(
        {
            path:"/mainbox",
            name:"mainbox",
            component:mainbox
        }
    )
    let {changeRouter} = useRouterStore()
    RouteConfig.forEach(item=>{
          //checkPermission(item.path) &&
          router.addRoute("mainbox",item)
    })
    //重定向
    router.addRoute("mainbox",{
        path:'/',
        redirect:"/index"
    })
     //404
    router.addRoute("mainbox",{
        path:"/:pathMatch(.*)*",
        name:"not found",
        component:NotFound
    })

    changeRouter(true)
}


//路由权限分配
// const checkPermission = (path) =>{
//     const { user } = useUserStore();
//     return user.role.rights(path)
// }
export default router






